# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: leon

import datetime
import functools

from coin.exchange.okex_futures.book_builder import BookBuilder
from coin.exchange.okex_futures.kr_rest.futures_product import OkexFuturesProduct
from coin.exchange.okex_base.okex_v3_handler_base import OkexV3HandlerBase


class FuturesTraits(object):
  @classmethod
  def get_qty_from_trade(cls, trade_msg, timestamp):
    if timestamp >= 1553832000000000000:  # == 20190329 4:00 UTC
      return float(trade_msg['qty'])
    else:
      # Okex Futures sent double-counted qty before 20190329 4:00 UTC.
      return float(trade_msg['qty']) / 2.

  @classmethod
  def get_product_from_instrument_id(cls, instrument_id, timestamp):
    as_of_timestamp = (timestamp // (1800 * 10**9)) * (1800 * 10**9)
    return cls._get_product_from_instrument_id_impl(instrument_id, as_of_timestamp)

  @classmethod
  @functools.lru_cache(maxsize=128)
  def _get_product_from_instrument_id_impl(cls, instrument_id, as_of_timestamp):
    current_time = datetime.datetime.fromtimestamp(as_of_timestamp / 1.e9)
    return OkexFuturesProduct.FromStrNativeProductV3(instrument_id, current_time)


class OkexFuturesHandler(OkexV3HandlerBase):
  BookBuilderType = BookBuilder
  TraitsType = FuturesTraits
